<template>
	<view class="app" style="padding: 10rpx;">
		<view v-if="member.is_plus_id" class="use-area dflex-b fwb ft-base margin-t0" style="background: #f5e7e6;"
			@click="toMember">
			<view>{{member.is_plus}}<text v-if="member.vip_price_discount">{{member.vip_price_discount}}折</text><text
					v-if="member.double_integral">,双倍积分</text><text v-if="member.partner">,分销合伙人</text>
			</view>
			<view class="iconfont iconjiantou-01 fs-sm ft-dark"></view>
		</view>
		<view v-if="!member.is_plus_id" class="use-area dflex-b fwb ft-base margin-t0" style="background: #f5e7e6;"
			@click="toMember">
			<view>开通会员,福利不断</view>
			<view class="iconfont iconjiantou-01 fs-sm ft-dark"></view>
		</view>
		<view style="background: #ffffff;padding: 20rpx;">
			<view class="text-xxl" style="font-size: 32rpx;text-align: center;">{{name}}</view>
			<view style="font-size: 32rpx;text-align: center;" v-if="description">{{description}}</view>
			<view v-if="type===0" style="font-size: 32rpx;text-align: center;">消费金额:{{(all_money-yj_money).toFixed(2)}}元
			</view>
			<!-- <view v-if="yj_money>0" style="font-size: 32rpx;text-align: center;">押金:{{yj_money}}元</view> -->
			<!-- <view v-if="type===0" style="font-size: 48rpx;text-align: center;">实际支付:{{money}}元</view> -->
		</view>
		<view v-if="type===1" style="background: #ffffff;padding: 20rpx;margin-top: 5rpx;">
			<input class="input" type="digit" v-model="payMoney" placeholder="请输入支付金额"
				placeholder-class="placeholder" />
		</view>
		<view style="background: #ffffff;padding: 20rpx;margin-top: 5rpx;" v-for="item  in content">
			<input class="input" v-model="item.value" :placeholder="'请输入'+item.title" placeholder-class="placeholder" />
		</view>
		<view class="padding-tb" v-if="vip_price_discount" style="background: #ffffff;margin-top: 5rpx;">
			<view class="padding-left dflex-b">
				<text class="flex-sub">会员优惠{{member.vip_price_discount}}折(不包含押金)</text>
				<text class="text-right flex-sub padding-right">优惠:{{vip_price_discount}}元</text>
			</view>
		</view>
		<view style="margin-top: 5rpx;">
			<use-list-title title="优惠券" :tip="couponName" color="#000000" iconfont="iconyouhui" rightColor="#000000"
				@goto="couponShow = true"></use-list-title>
		</view>
		<!-- 优惠券弹出层 -->
		<use-popup mode="bottom" bgclass=" " close-icon v-model="couponShow" @open="couponOpen">
			<!-- 优惠券区 -->
			<view class="coupon-area padding bg-drak border-radius-top30 safe-area-inset-bottom">
				<view class="tac fwbd w-full padding-lr  padding-top-xs padding-bottom fs-34">优惠券</view>
				<scroll-view scroll-y style="min-height: 40vh; max-height: 70vh;">
					<view v-for="(item, idx) in couponDatas" :key="idx"
						class="coupon-item bg-main pos-r fs-xs border-radius">
						<view class="content pos-r padding dflex-b">
							<view class="">
								<view class="margin-bottom-xs fs">{{ item.name }}</view>
								<view class="ft-dark">有效期至 {{ $api.format(item.end_time, 'yyyy-MM-dd') }}</view>
							</view>
							<view class="tar ">
								<view v-if="item.type == '满减'" :class="item.usable ? '' : 'ft-dark'"
									class="margin-bottom-xs price">{{ item.price }}</view>
								<view v-if="item.type == '折扣'" :class="item.usable ? '' : 'ft-dark'"
									class="margin-bottom-xs discount">{{ item.price }}</view>
								<view v-if="item.order_amount > 0" class="ft-dark">满{{ item.order_amount }}可用</view>
								<view v-else class="ft-dark">不限</view>
							</view>

							<view class="circle l"></view>
							<view class="circle r"></view>
						</view>
						<view class="dflex-b ">
							<text class="ft-dark padding-lr">{{ item.type }}</text>
							<text v-if="item.usable" class="ft-base padding-tb-sm padding-lr"
								@click="couponUse(item)">{{ item._id == order_coupon_id ? '不使用此券' : '立即使用' }}</text>
							<text v-else class="ft-dark padding-tb-sm padding-lr">不可使用</text>
						</view>
					</view>

					<view v-if="!(couponDatas && couponDatas.length > 0)" class="coupon-none">
						<text class="coupon-none-tip">无可用优惠券</text>
					</view>
				</scroll-view>
			</view>

		</use-popup>
		<view v-if="yj_money" class="padding-tb" style="background: #ffffff;margin-top: 5rpx;">
			<view class="padding-left dflex-b">
				<text class="flex-sub">押金</text>
				<text class="text-right flex-sub padding-right">{{yj_money}}元</text>
			</view>
		</view>
		<view class="padding-tb" style="background: #ffffff;margin-top: 5rpx;">
			<view class="padding-left dflex-b">
				<text class="flex-sub">实际支付</text>
				<text v-if="type===0" class="text-right flex-sub padding-right"
					style="font-size: 48rpx;">{{money}}元</text>
				<text v-else class="text-right flex-sub padding-right" style="font-size: 48rpx;">{{pay_money}}元</text>
			</view>
		</view>

		<view class="padding-tb" v-if="balanceMoney>0" style="background: #ffffff;margin-top: 5rpx;">
			<checkbox-group @change="useBalancePickChange" v-if="balanceMoney*100>(money*100-yj_money*100)">
				<label>
					<checkbox :checked="use_balance" style="margin-left: 20rpx;" />
					余额:{{balanceMoney}}元,可抵扣{{(money-yj_money).toFixed(2)}}元(押金不能使用余额)
				</label>
			</checkbox-group>
			<view v-else class="padding-left">
				<text>余额:{{balanceMoney}}元</text>
				<text class="margin-left" @click="toWallet">去充值</text>
			</view>
		</view>
		<view class="add-to-cart-btn" @click="confirm">
			<text class="cell-tit">立即支付</text>
		</view>
		<view v-if="wmz_ad_open" style="width: 96%;margin: 40rpx auto;">
			<template v-if="adversing_type">
				<ad :unit-id="wmz_ad_unit" ad-intervals="30"></ad>
			</template>
			<template v-else>
				<wmz-ad-banner :ad_unit="wmz_ad_unit" />
			</template>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	let spaceId
	let appId = 'def1da4565222ccc05d977461539689c'
	let shopId = 'def1da4565222ccc05d977461539689c'
	let _this;
	let _id
	export default {
		data() {
			return {
				all_money: 0,
				member: {},
				vip_price_discount: 0,
				order_coupon_id: "",
				use_balance: false,
				balanceMoney: '',
				content: [],
				yj_money: 0,
				type: "",
				name: "",
				description: "",
				money: "",
				phone: "",
				payMoney: "",
				authPlatform: "",
				authCode: "",
				user: null,
				wmz_ad_open: false,
				wmz_ad_unit: "",
				// 优惠券
				couponShow: false,
				couponName: '选择优惠券',
				couponDatas: [],
				// 优惠券类型 满减|折扣
				coupon_type: '满减',
				// 优惠券金额
				coupon_money: 0,
			}
		},
		onLoad(e) {
			_this = this
			// #ifdef MP-ALIPAY
			const alipayExtJson = my.getExtConfigSync();
			if (alipayExtJson && alipayExtJson.appId) {
				spaceId = alipayExtJson.spaceId;
				appId = alipayExtJson.appId;
				shopId = alipayExtJson.shopId;
			} else {
				let templateId = my.getAppIdSync().appId
				uni.setStorageSync("templateId", templateId)
			}
			// #endif

			// #ifdef MP-WEIXIN
			const wechatExtJson = uni.getExtConfigSync()
			if (wechatExtJson && wechatExtJson.appId) {
				spaceId = wechatExtJson.spaceId;
				appId = wechatExtJson.appId;
				shopId = wechatExtJson.shopId;
			} else {
				const accountInfo = wx.getAccountInfoSync();
				uni.setStorageSync("templateId", accountInfo.miniProgram.appId)
			}
			// #endif

			if (e.shopId) {
				shopId = e.shopId;
			}
			if (e.collectionId) {
				_id = e.collectionId
			}

			if (e.qrCode || e.q || uni.getStorageSync('qrCode')) {
				let scene = e.qrCode || e.q || uni.getStorageSync('qrCode');
				uni.setStorageSync('qrCode', scene);

				// #ifdef MP-WEIXIN
				scene = decodeURIComponent(scene);
				// #endif

				if (scene.indexOf("shopId") > -1) {
					shopId = scene.split("shopId=")[1].split("&")[0];
				}
				if (scene.indexOf("collectionId") > -1) {
					_id = scene.split("collectionId=")[1].split("&")[0];
				}
			}

			uni.setStorageSync('wmzmall_user_space_id', spaceId);
			uni.setStorageSync('wmzmall_user_app_id', appId);
			uni.setStorageSync('wmzmall_user_shop_id', shopId);
			this.getAuthCode()
			this.getCollection()
			// #ifdef MP-WEIXIN
			this.wxaAdverConfigGet()
			// #endif
		},
		methods: {
			...mapMutations(['login']),
			useBalancePickChange() {
				this.use_balance = !this.use_balance
			},
			toWallet() {
				uni.navigateTo({
					url: '/sub-user/pages/wallet/wallet'
				})
			},
			wxaAdverConfigGet() {
				this.$func.wmz_adver.call('wmzAdverCatering/adverShopConfigGet', {
					appId: appId,
					shopId: shopId,
					adProvider: "wx"
				}).then(res => {
					if (res.code === 200) {
						_this.wmz_ad_open = true
						_this.wmz_ad_unit = res.data.page_pay_before.adver_id
						_this.adversing_type = res.data.page_pay_before.adversing_type
					}
				})
			},
			toMember() {
				if (this.member && this.member.vip) {
					uni.navigateTo({
						url: '/sub-user/pages/member/member'
					})
					return;
				}

				uni.navigateTo({
					url: '/sub-user/pages/member/member-not'
				})
			},
			getCollection() {
				_this.$func.wmzmall.call('collection/get', {
					_id: _id
				}).then(res => {
					if (res.code === 200) {
						var data = res.datas.data;
						this.money = data.money
						this.yj_money = data.yj_money
						this.all_money = data.money
						this.name = data.name
						this.description = data.description
						this.type = data.type
						this.content = data.content
					} else {
						_this.$api.msg(res.msg);
						uni.switchTab({
							url: '../tabbar/introduce'
						})
					}
				}).catch(err => {
					console.log(err);
				});
			},
			getAuthCode() {
				// #ifdef MP-ALIPAY
				_this.authPlatform = 'alipay';

				uni.login({
					scopes: ['auth_base'],
					success(res) {
						if (res && res.code) {
							_this.authCode = res.code;
							_this.cloudLogin();
						} else {
							_this.$api.msg('获取支付宝授权码失败');
						}
					}
				});
				// #endif

				// #ifdef MP-WEIXIN
				_this.authPlatform = 'wechat';

				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success(res) {
						if (res && res.code) {
							_this.authCode = res.code;
							_this.cloudLogin();
						} else {
							_this.$api.msg('获取微信授权码失败');
						}
					}
				});
				// #endif
			},

			cloudLogin() {
				if (!_this.authCode) {
					_this.$api.msg('用户授权码参数丢失');
					return;
				}
				if (!_this.authPlatform) {
					_this.$api.msg('用户授权平台参数丢失');
					return;
				}

				let methodName;
				if ('alipay' === _this.authPlatform) {
					methodName = 'member/loginByAlipay';
				} else if ('wechat' === _this.authPlatform) {
					methodName = 'member/loginByWeixin';
				} else {
					_this.$api.msg('用户授权平台参数不正确');
					return;
				}
				let params = {
					app_id: appId,
					code: _this.authCode,
					templateId: uni.getStorageSync("templateId")
				};
				_this.$func.wmzmall.call(methodName, params).then(res => {
					if (res && res.code && 200 === res.code && res.datas) {
						_this.login(res.datas);
						if (res.datas.user) {
							_this.user = res.datas.user;
						}
						if (res.datas.member) {
							_this.member = res.datas.member;
							if (_this.member.member_amount) {
								_this.balanceMoney = (_this.member.member_amount / 100).toFixed(2);
								if (this.balanceMoney * 100 > (this.money * 100 - this.yj_money * 100)) {
									this.use_balance = true
								}
							}
							if (_this.member.vip_price_discount) {
								_this.vip_price_discount = ((_this.all_money - _this.yj_money) - (_this.all_money -
											_this.yj_money) * _this.member
										.vip_price_discount)
									.toFixed(2)
								_this.money = (_this.money - _this.vip_price_discount).toFixed(2)
							}
						}
					} else if (res.msg) {
						_this.$api.msg(res.msg);
					} else {
						_this.$api.msg('用户授权登录失败');
					}
				}).catch(err => {
					console.log(err);
				});
			},
			input(e) {
				this.money = e
				this.currentDishessId = ""
				this.currentQuickOrderId = ""
			},
			// 打开优惠券
			couponOpen() {
				// 加载可使用优惠券数据 couponDatas
				this.$func.wmzmall.call('marketing/coupon/useOrder', {
					goods_ids: [_id]
				}).then(res => {
					if (res.code == 200) {
						res.datas.forEach(x => {
							switch (x.type) {
								case '满减':
									x.price /= 100;
									x.usable = (this.money - this.yj_money) > x.price;
									break;
								case '折扣':
									x.price /= 100;
									x.usable = (this.money - this.yj_money) * x.price > 0;
									break;
								default:
									break;
							}

							if (x.order_amount && x.usable) {
								// 金额大于等于满减金额
								x.usable = (this.money - this.yj_money) >= x.order_amount;
							}
						});
						this.couponDatas = res.datas;
						return;
					}

					this.$api.msg(res.msg);
				})
			},
			// 使用优惠券
			couponUse(coupon) {
				if (this.order_coupon_id == coupon._id) {
					this.order_coupon_id = '';
					this.coupon_money = 0;
					this.money = (this.money * 1 + coupon.price * 1).toFixed(2)
					this.couponName = ""
				} else {
					this.couponShow = false;
					this.order_coupon_id = coupon._id;
					this.coupon_money = coupon.price;
					this.money = (this.money - coupon.price).toFixed(2)
					this.couponName = coupon.name;
				}
				this.couponShow = false;
			},
			//确认支付
			confirm: function() {
				if (this.type === 1) {
					if (!this.payMoney) {
						uni.showToast({
							title: '请输入支付金额',
							icon: 'none',
						});
						return;
					}
				}
				let content = this.content
				for (var i in content) {
					if (content[i].required && !content[i].value) {
						uni.showToast({
							title: '请输入' + content[i].title,
							icon: 'none',
						});
						return;
					}
				}
				let payWay;
				if ('alipay' === _this.authPlatform) {
					payWay = '支付宝';
				} else if ('wechat' === _this.authPlatform) {
					payWay = '微信支付';
				}
				uni.showLoading();
				let params = {
					collectionId: _id,
					phone: this.phone,
					appId: appId,
					shopId: shopId,
					authCode: _this.authCode,
					authPlatform: _this.authPlatform,
					payWay: payWay,
					payMoney: _this.payMoney,
					content: content,
					use_balance: _this.use_balance,
					order_coupon_id: this.order_coupon_id
				};
				_this.$func.wmzmall.call('collection/pay', params).then(res => {
					if (res.code === 200) {
						if (_this.use_balance && _this.yj_money <= 0) {
							uni.hideLoading();
							uni.redirectTo({
								url: '/pages/collection/paySuccess?money=' + _this
									.money
							});
						} else {
							var data = res.datas.data;
							// #ifdef MP-WEIXIN
							uni.requestPayment({
								provider: 'wxpay',
								timeStamp: data.timeStamp,
								nonceStr: data.nonceStr,
								package: data.package,
								signType: data.signType,
								paySign: data.paySign,
								success: res => {
									uni.hideLoading();
									uni.redirectTo({
										url: '/pages/collection/paySuccess?money=' + _this
											.money
									});
								},
								fail: res => {
									uni.showToast({
										title: '已取消支付',
										icon: 'none',
									});
									uni.hideLoading();
								},
								complete: () => {},
							});
							// #endif
							// #ifdef MP-ALIPAY
							uni.requestPayment({
								provider: 'alipay',
								tradeNO: data.trade_no,
								success: res => {
									uni.hideLoading();
									if (res.resultCode === '9000') {
										uni.redirectTo({
											url: '/pages/collection/paySuccess?money=' +
												_this
												.money
										});
									} else if (res.resultCode === '6001') {
										uni.showToast({
											title: '已取消支付',
											icon: 'none',
										});
										uni.hideLoading()
									}
								},
								fail: res => {
									uni.showToast({
										title: '已取消支付',
										icon: 'none',
									});
									uni.hideLoading();
								},
								complete: () => {
									uni.hideLoading();
								},
							});
							// #endif
						}
					} else {
						uni.hideLoading();
						_this.$api.msg(res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
					_this.$api.msg("支付失败,请退出刷新重试");
				});
			},
		},
	}
</script>

<style lang="scss">
	page {
		background: #f5f5f5;
	}

	.add-to-cart-btn {
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #DBA871;
		color: #ffffff;
		font-size: 26rpx;
		height: 80rpx;
		border-radius: 12rpx;
		margin-top: 100rpx;
	}

	/* 优惠券区 */
	.coupon-area {

		.coupon-item {
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.content {
				&:after {
					position: absolute;
					left: 0;
					bottom: 0;
					content: '';
					width: 100%;
					height: 0;
					border-bottom: 1px dashed #f3f3f3;
					transform: scaleY(50%);
				}
			}

			.circle {
				position: absolute;
				bottom: -10rpx;
				z-index: 10;
				width: 20rpx;
				height: 20rpx;
				background: #f5f5f5;
				border-radius: 50%;

				&.r {
					right: -6rpx;
				}

				&.l {
					left: -6rpx;
				}
			}
		}
	}
</style>